import 'dart:convert';

import 'package:core_package/core_package.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'dart:ui' as ui show window;

import 'package:flutter_app_unionad/model/province_model.dart';
import 'package:flutter_app_unionad/request/facility_request.dart';

/*
* 选择 省--市---县 widget  需要 showModalBottomSheet 配合使用
* */
class ShowSelectAddressDialog extends StatefulWidget {
  final String? title;
  final Function(ProvinceModel province, ProvinceModel city, ProvinceModel county)? onSelected;

  final Color? unselectedColor;
  final Color? selectedColor;

  final double? itemTextFontSize;
  final TextStyle? titleTextStyle;

  ShowSelectAddressDialog(
      {Key? key,
      @required this.onSelected,
      this.title = "选择地址",
      this.unselectedColor: Colors.grey,
      this.selectedColor: Colors.blue,
      this.itemTextFontSize: 14.0,
      this.titleTextStyle: const TextStyle(fontSize: 16.0, color: Colors.black, fontWeight: FontWeight.bold)})
      : super(key: key);

  static Future showAddress(
    BuildContext context, {
    String title = "选择地址",
    @required Function(ProvinceModel province, ProvinceModel city, ProvinceModel county) ?onSelected,
    Color unselectedColor = Colors.grey,
    Color selectedColor = Colors.blue,
    double itemTextFontSize = 14.0,
    TextStyle titleTextStyle = const TextStyle(fontSize: 16.0, color: Colors.black, fontWeight: FontWeight.bold),
  }) async {
    return showModalBottomSheet(
        context: context,
        builder: (ctx) {
          return ShowSelectAddressDialog(
            onSelected: onSelected,
            title: title,
            unselectedColor: unselectedColor,
            selectedColor: selectedColor,
            itemTextFontSize: itemTextFontSize,
            titleTextStyle: titleTextStyle,
          );
        });
  }

  @override
  _ShowSelectAddressDialogState createState() => _ShowSelectAddressDialogState();
}

class _ShowSelectAddressDialogState extends State<ShowSelectAddressDialog> with TickerProviderStateMixin {
  int _index = 0;
  TabController? _tabController;
  ScrollController? _scrollController;

  /// TabBar不能动态加载，所以初始化3个，其中两个文字置空，点击事件拦截住。
  List<Tab> myTabs = <Tab>[Tab(text: '请选择'), Tab(text: ''), Tab(text: '')];

  List<ProvinceModel> provinces = <ProvinceModel>[];
  List<ProvinceModel> cities = <ProvinceModel>[];
  List<ProvinceModel> counties = <ProvinceModel>[];

  //当前列表数据
  List<ProvinceModel> mList = <ProvinceModel>[];

  ///三级联动的position
  var _position = [0, 0, 0];
  double itemHeight = 48.0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController = ScrollController();
    _tabController = TabController(length: myTabs.length, vsync: this);
    _initData();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Material(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(SizeFill.setRx(10)),
          topRight: Radius.circular(SizeFill.setRx(10)),
        ),
        color: Colors.white,
        child: Container(
          height: SizeFill.screenHeight * 9 / 16,
          child: Column(
            children: [
              Container(
                width: double.infinity,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: SizeFill.setRx(15), vertical: SizeFill.setRx(12)),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        widget.title ?? '',
                        style: TextStyle(
                          color: MyColors.color_34_34_34,
                          fontWeight: FontWeight.w500,
                          fontSize: MyFont.font18,
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () => NavigatorUtil.pop(context),
                      child: Image.asset(
                        MyAssetsImages.setAssetsImagesPath("icon_close.png"),
                        width: SizeFill.setRx(20),
                        height: SizeFill.setRx(20),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 8),
              Container(
                height: 36,
                color: Colors.white,
                alignment: Alignment.centerLeft,
                child: TabBar(
                  controller: _tabController,
                  isScrollable: true,
                  onTap: (index) {
                    if (myTabs[index].text == null || myTabs[index].text!.isEmpty) {
                      _tabController?.animateTo((_index));
                      return;
                    }
                    switch (index) {
                      case 0:
                        mList = provinces;
                        break;
                      case 1:
                        mList = provinces[_position[0]].cityList!;
                        break;
                      case 2:
                        mList = cities[_position[1]].areaList!;
                        break;
                    }
                    setState(() {
                      _index = index;
                      _scrollController?.animateTo(
                        _position[_index] * itemHeight,
                        duration: Duration(milliseconds: 10),
                        curve: Curves.ease,
                      );
                    });
                  },
                  indicatorSize: TabBarIndicatorSize.label,
                  unselectedLabelColor: MyColors.color_35_35_35,
                  labelColor: widget.selectedColor,
                  tabs: myTabs,
                  indicatorColor: widget.selectedColor,
                ),
              ),
              Divider(height: 1, color: MyColors.color_238_238_238),
              Expanded(
                child: provinces.length > 0 ? _buildListView() : CupertinoActivityIndicator(animating: false),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _initData() async {
    FacilityRequest.getAllProvince(context).then((value) {
      setState(() {
        provinces = value;
        mList = provinces;
      });
    });
  }

  Widget _buildListView() {
    return ListView.builder(
        controller: _scrollController,
        itemBuilder: (context, index) => InkWell(
            child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                height: itemHeight,
                alignment: Alignment.centerLeft,
                child: Row(children: <Widget>[
                  Text(mList[index].name??'',
                      style: TextStyle(
                          fontSize: widget.itemTextFontSize,
                          color: mList[index].name == myTabs[_index].text
                              ? widget.selectedColor
                              : widget.unselectedColor)),
                  SizedBox(height: 8),
                  Offstage(
                      offstage: mList[index].name != myTabs[_index].text,
                      child: Icon(Icons.check, size: 16.0, color: widget.selectedColor))
                ])),
            onTap: () {
              myTabs[_index] = Tab(text: mList[index].name);
              _position[_index] = index;
              _index++;
              switch (_index) {
                case 1:
                  mList = cities = provinces[_position[0]].cityList!;
                  myTabs[1] = Tab(text: "请选择");
                  myTabs[2] = Tab(text: "");
                  break;
                case 2:
                  mList = counties = cities[_position[1]].areaList!;
                  myTabs[2] = Tab(text: "请选择");
                  break;
                case 3:
                  _index = 2;
                  widget.onSelected?.call(provinces[_position[0]], cities[_position[1]], counties[_position[2]]);
                  NavigatorUtil.pop(context);
                  break;
              }
              setState(() {});
              _scrollController?.animateTo(0.0, duration: Duration(milliseconds: 100), curve: Curves.ease);
              _tabController?.animateTo(_index);
            }),
        itemCount: mList.length);
  }
}
